<template>
  <div class="detail-page">
    <van-nav-bar
      fixed
      @click-left="$router.back()"
      left-text="返回"
      title="面经详情"
    />

    <header class="header">
      <h1>{{ detail.stem }}</h1>
      <p>
        {{ detail.createdAt }} | {{ detail.views }} 浏览量 |
        {{ detail.likeCount }} 点赞数
      </p>
      <p>
        <img :src="detail.avatar" alt="" />
        <span>{{ detail.creator }}</span>
      </p>
    </header>

    <main class="body" v-html="detail.content"></main>
    <div class="opt">
      <van-icon
        @click="update(1)"
        :class="{ active: detail.likeFlag === 1 }"
        name="like-o"
      />
      <van-icon
        @click="update(2)"
        :class="{ active: detail.collectFlag === 1 }"
        name="star-o"
      />
    </div>
  </div>
</template>

<script>
import { getDetailByIdAPI, likeAndCollectAPI } from "@/api/article";

export default {
  data() {
    return {
      detail: {},
    };
  },

  async created() {
    const { data } = await getDetailByIdAPI(this.$route.params.id);
    this.detail = data;
  },
  methods: {
    async update(optType) {
      await likeAndCollectAPI(this.$route.params.id, optType);

      if (optType === 1) {
        if (this.detail.likeFlag === 0) {
          this.detail.likeFlag++;
          this.detail.likeCount++;
          this.$toast("点赞成功");
        } else {
          this.detail.likeFlag--;
          this.detail.likeCount--;
          this.$toast("取消点赞");
        }
        return;
      }

      if (this.detail.collectFlag === 0) {
        this.detail.collectFlag++;
        this.$toast("收藏成功");
      } else {
        this.detail.collectFlag--;
        this.$toast("取消收藏");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.detail-page {
  margin-top: 44px;
  overflow: hidden;
  padding: 0 15px;
  .header {
    h1 {
      font-size: 24px;
    }
    p {
      color: #999;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .opt {
    position: fixed;
    bottom: 100px;
    right: 0;
    > .van-icon {
      margin-right: 20px;
      background: #fff;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      box-shadow: 2px 2px 10px #ccc;
      font-size: 18px;
      &.active {
        background: #fec635;
        color: #fff;
      }
    }
  }
}
</style>
